/*
 * Grupo:		Danilo Beraldo Ireno
 * 				Flavio Augusto de Mello
 * 				Giuliano G. Maranha
 * 				Luis Fernando Junior
 *
 * Disciplina: 	Compiladores
 * Professor:	Dr. Eraldo Pereira Marinho*
 */

#include <string.h>
#include <stdio.h>

#include "symtab.h"


/*
 * symtab_dispose
 * symtab_lookup
 * symtab_insert
 */

int idlex_index = 0;
char idlex_tape[MAXIDLEXLEN];
int symtab[MAXSYMTABENTRIES][MAXSYMTABCOLUMNS];

/**
 * Symtab Columns

 * [0] = idLexIndex
 * [1] = lexemeSize
 * [2] = type
 * [3] = lexLevel
 */

int symtab_nextentry = 0;

int symtab_lookup(char const *query, int const lexLevel)
{
	int symtabEntry = 0;
	int i = 0;

	for(i = 0; i< symtab_nextentry;i++){


		int lexIndexFirst = symtab[i][0];
		int lexIndexLast = symtab[i][0] + symtab[i][1];

		char lexemeFound[MAXIDLEXLEN];
		int temp = 0;
		int x = lexIndexFirst;

		for(x = lexIndexFirst;x<lexIndexLast;x++){

			lexemeFound[temp] =  idlex_tape[x];
			temp++;
		}
		lexemeFound[temp] = 0;

		if(strcmp(lexemeFound,query) == 0 && symtab[i][3] == lexLevel){

			return i;
		}
	}

	return -1;
}

int symtab_insert(int lexLevel, int type, char const *lexeme){

	int lexemeSize = strlen(lexeme);

	if(symtab_lookup(lexeme,lexLevel) >= 0){
		printf("Semantic Error: Lexeme already exists!\n");
		return -1;
	}else{
		if(symtab_nextentry == MAXSYMTABENTRIES){
			printf("Semantic Error: SymTab Overflow!\n");
			return -2;
		}else{
			if((MAXIDLEXLEN - idlex_index) < lexemeSize){
				printf("Semantic Error: Symbols tape overflow!\n");
				return -3;
			}else{

					symtab[symtab_nextentry][0] = idlex_index;
					symtab[symtab_nextentry][1] = lexemeSize;
					symtab[symtab_nextentry][2] = type;
					symtab[symtab_nextentry][3] = lexLevel;

					int i = 0;

					for(i = 0;i<lexemeSize;i++){

						idlex_tape[idlex_index] = lexeme[i];
						idlex_index++;
					}
					symtab_nextentry++;
			}
		}
	}
}
